package com.janko.sccommon.util;

import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.io.*;

/**
 * @Author nyk
 * @Date 2021/5/24 16:27
 * @Version 1.0
 * @Desc PDF操作相关工具类
 */
public class AsposePDFUtil {
    static Logger log = LoggerFactory.getLogger(AsposePDFUtil.class);
    private static  AsposePDFUtil instance;
    private static boolean excelLicensetResoult = false;
    public AsposePDFUtil() {
    }
    public static synchronized  AsposePDFUtil getInstance() {
        if (instance == null) {
            instance = new AsposePDFUtil();
        }
        return instance;
    }

    /**
     * 获取授权码
     * @return 返回授权码是否验证成功
     */
    public boolean getExcelLicense() {
        boolean result = false;
        try {
            // license.xml应放在..\WebRoot\WEB-INF\classes路径下
//            InputStream is = AsposePDFUtil.class.getClassLoader().getResourceAsStream("classpath:/license.xml");
            InputStream is = new BufferedInputStream(new FileInputStream("D:\\a.xml"));
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * excel转PDF
     * @param fromExcelFile Excel本地文件
     * @param toPDFFile 生成的PDF文件路径信息
     */
    public static void excel2Pdf(String fromExcelFile, File toPDFFile) {
        if (!excelLicensetResoult) {
            // 验证License 若不验证则转化出的pdf文档会有水印产生
            excelLicensetResoult = getInstance().getExcelLicense();
            if (!excelLicensetResoult) {
                return;
            }
        }
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            Workbook wb = new Workbook(fromExcelFile);// 原始excel路径
            os = new FileOutputStream(toPDFFile);
            //pdf展示处理
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
            pdfSaveOptions.setPdfExportImagesFolder(toPDFFile.getParent());
            wb.save(os, pdfSaveOptions);
            os.close();
            long now = System.currentTimeMillis();
            log.info("excel2Pdf共耗时：" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + toPDFFile.getPath()); //转化过程耗时
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
    }

    private static int interval = -5;

    /**
     * 打印水印
     * @param inputFile 源文件位置
     * @param outputFile 输出文件位置
     * @param waterMarkName 水印文字内容
     * @param isBackgroundText 背景全屏水印是否显示
     */
    public static void waterMarkOnce(String inputFile, String outputFile, String waterMarkName, Boolean isBackgroundText) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",  BaseFont.EMBEDDED);
            com.itextpdf.text.Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            // 设置透明度
            gs.setFillOpacity(0.3f);
            gs.setStrokeOpacity(0.8f);
            int total = reader.getNumberOfPages() + 1;
            if (isBackgroundText) {
                PdfContentByte under;
                //遍历多少个PDF页
                for (int i = 1; i < total; i++) {
                    pageRect = reader.getPageSizeWithRotation(i);
                    under = stamper.getOverContent(i);
                    under.saveState();
                    under.setGState(gs);
                    under.beginText();
                    under.setFontAndSize(base, 45);  //设置大小
                    // 设置水印颜色
                    under.setColorFill(BaseColor.RED);
                    under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, reader.getPageSize(i).getWidth() / 2, reader.getPageSize(i).getHeight() / 2, 45);
                    // 添加水印文字
                    under.endText();
                }
            }

            String waterBack="西岗供应商2021年5月23日提交，钱凯灵在2021年5月23日通过";
            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 0;
            int textW = 0;
            label.setText(waterBack);
            metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight()+40;
            textW = metrics.stringWidth(label.getText());
            PdfContentByte under2;
            int numj = 0;
            int numk = 0;
            //遍历多少个PDF页
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under2 = stamper.getOverContent(i);
                under2.saveState();
                under2.setGState(gs);
                under2.beginText();
                under2.setFontAndSize(base, 16);  //设置大小
                // 设置水印颜色
                under2.setColorFill(BaseColor.BLACK);
                // 水印文字成30度角倾斜
                // 你可以随心所欲的改你自己想要的角度
                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 3) {
                    numj ++ ;
                    for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW ) {
                        numk ++ ;
                        //给水印添加45°的倾斜
                        under2.showTextAligned(Element.ALIGN_LEFT, waterBack, width - textW, height - textH,40);
                    }
                }
                // 添加水印文字
                under2.endText();
            }
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 全屏幕打印水印文字
     * @param inputFile 源文件位置
     * @param outputFile 输出文件位置
     * @param waterMarkName 水印文字内容
     */
    public static void waterMarkAllPrint(String inputFile, String outputFile, String waterMarkName) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",  BaseFont.EMBEDDED);
            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            // 设置透明度
            gs.setFillOpacity(0.3f);
            gs.setStrokeOpacity(0.4f);
            int total = reader.getNumberOfPages() + 1;

            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 0;
            int textW = 0;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight() + 10;
            textW = metrics.stringWidth(label.getText()) + 10;

            PdfContentByte under;
            int numi = 0 ;
            int numj = 0 ;
            int numk = 0 ;
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                under.setFontAndSize(base, 16);  //设置大小
                // 设置水印颜色
                under.setColorFill(BaseColor.BLACK);
                // 水印文字成30度角倾斜
                // 你可以随心所欲的改你自己想要的角度
                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 3) {
                    numj ++ ;
                    for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 2) {
                        numk ++ ;
                        //给水印添加45°的倾斜
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH,40);
                    }
                }
                // 添加水印文字
                under.endText();
            }
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
//        File file = new File("d:\\demo.pdf");
//        excel2Pdf("D:\\demo.xlsx", file);
        waterMarkOnce("D:\\demo.pdf", "D:\\demo_water.pdf", "已归档", true);
//          waterMarkAllPrint("D:\\demo.pdf","D:\\demoAll_water.pdf","已归档");
    }
}
